package summary;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/9 9:14
 * https://leetcode-cn.com/problems/valid-anagram/
 */
public class Title242 {

    public static boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        HashMap<Character, Integer> hashS = new HashMap<>();
        HashMap<Character, Integer> hashT = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            hashS.put(s.charAt(i), hashS.getOrDefault(s.charAt(i), 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            hashT.put(t.charAt(i), hashT.getOrDefault(t.charAt(i), 0) + 1);
        }
        Set<Character> characters = hashS.keySet();
        for (char c : characters) {
            if (!hashS.get(c).equals(hashT.get(c))) {
                return false;
            }
        }
        return true;
    }

    public static boolean isAnagram1(String s, String t) {
        int[] record = new int[26];
        for (int i = 0; i < s.length(); i++) {
            record[s.charAt(i) - 'a'] += 1;
        }
        for (int i = 0; i < t.length(); i++) {
            record[t.charAt(i) - 'a'] -= 1;
        }
        for (int i = 0; i < record.length; i++) {
            if (record[i] != 0) {
                return false;
            }
        }
        return true;
    }






    public boolean isAnagram2(String s, String t) {
        Map<Character, Integer> hashS = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            hashS.put(c, hashS.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            if (hashS.containsKey(c)) {
                Integer integer = hashS.get(c);
                if (integer == 1) {
                    hashS.remove(c);
                }else{
                    hashS.put(c, integer - 1);
                }
            }else{
                return false;
            }
        }
        return hashS.isEmpty();
    }








    public static void main(String[] args) {
        isAnagram("rat", "car");
    }
}
